import axios from "axios";
import { message } from 'ant-design-vue'
import router from "../router";
import store from "@/store";
import qs from "qs";
import { getToken } from "@/utils/auth";
const service = axios.create({
  baseURL: "/api",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  timeout: 30000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['Authorization'] = `${getToken()}`;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data;
    return Promise.resolve(res);
  },
  error => {
    if (error.response.status === 401) {
      // 401 错误，重定向到登录页
      store.dispatch('user/logout').then(() => {
        router.push(`/login?redirect=${window.location.pathname}`);
      });
    }
    return Promise.reject(error);
  }
);

export default service;
